<template>
  <div class="ano-page ano-design"  @click="onAnoDesignClick">
    <AnoDesignHeader />
    <div class="ano-design-container">
      <div class="design-panel">
        <ul class="panel-menus">
          <li 
            class="item" 
            v-for="(item, index) in menus" 
            :class="{'active': index === activeMenuIndex}"
            :key="item.menuId"
            @click="handleSwitchMenu(index)">
            <div class="icon icon-text" :class="item.icon"></div>
            <div class="txt">{{ item.title }}</div>
          </li>
        </ul>
        <div class="panel-content">
          <!-- <div class="panel-hd">
            <div class="title">{{ menus[activeMenuIndex].title }}</div>
            <div class="close">
              <i class="el-icon-close"></i>
            </div>
          </div> -->
          <component
            v-if="activeDesignComponent"
            :is="activeDesignComponent"
            :imageInfo="activeDesign"
            :activeImageIndex="activeImageIndex"
            :maxZIndex="maxZIndex"
            :minZIndex="minZIndex"
            :key="designComponentKey"
            @designAdd="onDesignAdd"
            @designChange="onDesignChange"></component>
          <div class="ano-panel ano-panel-default" v-else>
            <div class="hd">你想如何开始？</div>
            <div class="bd">
              <ul class="menu-list">
                <li class="item" 
                  v-for="(item, index) in defMenus" 
                  :key="item.menuId"
                  @click="handleSwitchMenu(index)">
                  <div class="pic"></div>
                  <div class="txt">{{ item.title }}</div>
                </li>
              </ul>
            </div>
            <div class="fd">或<span class="stg">重新开始</span></div>
          </div>
        </div>
      </div>
      <div class="design-canvas">
        <div class="canvas-sample">
          <img
            class="pic"
            src="../../assets/imgs/panel_sample.png"
            alt="t-shirt"
          />
        </div>
        <div class="canvas-main" ref="canvasMain" :class="{'selected': activeImageIndex >= 0}">
          <template v-for="(item, index) in designImages">
              <!-- :active="activeImageIndex === index" -->
            <!-- :prevent-deactivation ="activeImageIndex === index" -->
            <AnoDesignPanel
              class="design-itemBox"
              :active="activeImageIndex === index"
              :prevent-deactivation="true"
              :x="item.left || 0"
              :y="item.top || 0"
              :w="item.width || 1"
              :h="item.height || 1"
              :parent="true"
              :handles="['br']"
              :lock-aspect-ratio="false"
              drag-handle=".design-box-wrap"
              class-name-handle="design-zoom"
              :key="index"
              :style="{zIndex: item.isLayerTop ? item.zIndex : 0}"
              @resizing="onResize" 
              @dragging="onDrag"
              @activated="onActived(index)"
              @deactivated="onDeactivated"
              @dragstop="onDragstop"
              @resizestop="onResizestop">
              <div ref="imgItem" class="design-box-wrap" :class="{'ano-rotateY180': item.isRotateY, 'ano-rotateX180': item.isRotateX}">
                <img class="design-box-lay" :src="getRealImgUrl(item)" alt="img" @load="onImageLoad($event, index)">
                <img class="design-box-img" :src="getRealImgUrl(item)" :alt="item.txt">
              </div>
              <div class="design-close" @click="handleDesignRemove(index)"></div>
              <!-- <div class="design-zoom"></div> -->
            </AnoDesignPanel>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AnoDesignPanel from 'vue-draggable-resizable'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'

import AnoDesignHeader from './components/anoDesignHeader'
import AnoTextPanel from './components/anoTextPanel'
import AnoArtPanel from './components/anoArtPanel'
import AnoUploadPanel from './components/anoUploadPanel'
import AnoColorPanel from './components/anoColorPanel'
import AnoNotePanel from './components/anoNotePanel'
import AnoColors from './components/anoColors'

import { mapGetters, mapMutations } from 'vuex'

export default {
  name: "design",
  components: {
    AnoDesignHeader,
    AnoDesignPanel,
    AnoTextPanel,
    AnoArtPanel,
    AnoUploadPanel,
    AnoColorPanel,
    AnoNotePanel,
    AnoColors,
  },
  data() {
    return {
      menus: [
        { title: '添加文字', icon: 'icon-text', menuId: 1, component: 'AnoTextPanel' },
        { title: '添加艺术图', icon: 'icon-image', menuId: 2, component: 'AnoArtPanel' },
        { title: '上传图片', icon: 'icon-upload', menuId: 3, component: 'AnoUploadPanel' },
        { title: '衣服颜色', icon: 'icon-color', menuId: 4, component: 'AnoColorPanel' },
        // { title: '添加名字', icon: 'icon-color', menuId: 5 },
        { title: '添加备注', icon: 'icon-note', menuId: 6, component: 'AnoNotePanel' },
      ],
      defMenus: [
        { title: '添加文字', icon: 'icon-text', menuId: 1, component: 'AnoTextPanel' },
        { title: '添加艺术图', icon: 'icon-image', menuId: 2, component: 'AnoArtPanel' },
        { title: '上传图片', icon: 'icon-upload', menuId: 3, component: 'AnoUploadPanel' },
        { title: '更换产品', icon: 'icon-color', menuId: 4, component: 'AnoColorPanel' },
      ],
      
      designComponentKey: 1,
      // 所有自定义图片
      designImages: [
        // {
        //   url: 'http://www.cabage.cn/project/x/draw/word?txt=%E5%A4%A7%E4%BD%AC%E5%A5%BD&fontFamily=%E5%AE%8B%E4%BD%93&fontSize=200&colorR=20&colorG=100&colorB=200&outLine=false&outLineR=100&outLineG=100&outLineB=200&outLineSize=8&hide=false&angle=68',
        //   width: 0,
        //   height: 0,
        //   left: 0,
        //   top: 0,
        //   txt: 'AAA',
        //   fontFamily: '',
        //   fontSize: 200,
        //   fontColor: '',
        //   colorR: '100',
        //   colorG: '100',
        //   colorB: '100',
        //   outLine: false,
        //   outlineColor: '',
        //   outLineR: '100',
        //   outLineG: '100',
        //   outLineB: '100',
        //   outLineSize: 8,
        //   hide: false,
        //   angle: 0,
        //   type: 'text',
        //   isLocked: true,
        //   hasLock: false,
        //   isSelected: false
        // },
        // {
        //   url: 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2583260997,1860491548&fm=26&gp=0.jpg',
        //   width: 80,
        //   height: 80,
        //   left: 100,
        //   top: 120,
        //   txt: 'AAA',
        //   fontFamily: '',
        //   fontSize: 200,
        //   fontColor: '',
        //   colorR: '100',
        //   colorG: '100',
        //   colorB: '100',
        //   outLine: false,
        //   outlineColor: '',
        //   outLineR: '100',
        //   outLineG: '100',
        //   outLineB: '100',
        //   outLineSize: 8,
        //   hide: false,
        //   angle: 0,
        //   type: 'art',
        //   isLocked: true,
        //   hasLock: true,
        //   isSelected: false
        // }
      ],

      // baseIndex: 1,
    }
  },
  computed: {
    ...mapGetters({
      // designImages: 'getDesignImages',
      activeImageIndex: 'getActiveImageIndex',
      activeDesignComponent: 'getActiveDesignComponent',
      activeMenuIndex: 'getActiveDesignMenuIndex'
    }),
    activeMenu() {
      return this.menus[this.activeMenuIndex]
    },
    activeDesignImage() {
      if (!this.activeImageIndex) {
        return null
      }
      return this.designImages[this.activeImageIndex]
    },
    activeDesign() {
      return this.designImages[this.activeImageIndex];
    },
    maxZIndex() {
      let maxZIndex = 0;
      this.designImages.forEach(item => {
        if(item.zIndex > maxZIndex) {
          maxZIndex = item.zIndex
        }
      })
      return maxZIndex + 1;
    },
    minZIndex() {
      let minZIndex = 0;
      this.designImages.forEach(item => {
        if(item.zIndex < minZIndex) {
          minZIndex = item.zIndex
        }
      })
      return minZIndex - 1;
    }
  },
  methods: {
    ...mapMutations([
      'setActiveImageIndex',
      'setActiveDesignMenuIndex',
      'setActiveDesignComponent',
    ]),
    getRealImgUrl(img) {
      if (img.type === 'text') {
        let baseUrl = 'http://www.cabage.cn/project/x/draw/word'
        return `${baseUrl}?txt=${img.txt}&fontFamily=${img.fontFamily}&fontSize=${img.fontSize}&colorR=${img.colorR}&colorG=${img.colorG}&colorB=${img.colorB}&outLine=${img.outLine}&outLineR=${img.outLineR}&outLineG=${img.outLineG}&outLineB=${img.outLineB}&outLineSize=${img.outLineSize}&hide=${img.hide}&angle=${img.angle}`
      }
      return img.url
    },
    handleSwitchMenu(index) {
      console.log(2, '--handleSwitchMenu-')
      // 标识点击过菜单,解决点击菜单时，到不了对应组件问题
      this.isActiveMenu = true;
      this.setActiveImageIndex(-1)
      this.setActiveDesignMenuIndex(index);
      this.setActiveDesignComponent(this.menus[index].component)
    },
    onDesignAdd(res) {
      console.log(res, '--onDesignAdd---')
      this.designImages.push({
        ...res,
        isSelected: true
      })
      this.setActiveImageIndex(this.designImages.length - 1)
    },
    onDesignChange(res) {
      console.log(res, '--onDesignChange---')
      if (res.isCenter) {
        let parentWidth = this.$refs['canvasMain'].clientWidth;
        let designItemWidth = this.$refs['imgItem'][this.activeImageIndex].offsetWidth;
        res.left = (parentWidth - designItemWidth)/2
      }
      let newDesign = Object.assign({}, this.designImages[this.activeImageIndex], res)
      this.designImages.splice(this.activeImageIndex, 1, newDesign)
    },
    onImageLoad(e, imgIndex) {
      if (e.path[0] && e.path[0].tagName === 'IMG') {
        this.designImages[imgIndex].width = e.path[0].width;
        this.designImages[imgIndex].height = e.path[0].height;
        this.$forceUpdate()
      }
      console.log(e, '---onImageLoad-', e.path[0], imgIndex, this.designImages[imgIndex])
    },
    onActived(index) {
      console.log(index, '--onActived-')
      this.setActiveImageIndex(index)
      this.designComponentKey += 1;
      if (this.designImages[index].type === 'text') {
        this.setActiveDesignMenuIndex(0);
        this.setActiveDesignComponent(this.menus[0].component)
        return;
      }
      this.setActiveDesignMenuIndex(1);
      this.setActiveDesignComponent(this.menus[1].component)
    },
    onDeactivated(e) {
      console.log(1, '--onDeactivated-', e)
      // if (this.isActiveMenu) {
      //   this.setActiveDesignComponent(this.menus[this.activeMenuIndex].component)
      //   return;
      // }
      // this.setActiveDesignComponent('')
      // 图片失去焦点放当前组件点击事件里
      // this.setActiveImageIndex(-1)
    },
    onResize (x, y, width, height) {
      console.log(this.designImages[this.activeImageIndex], '---', x, y, width, height)
      this.designImages[this.activeImageIndex].isCenter = false
      this.designImages[this.activeImageIndex].left = x
      this.designImages[this.activeImageIndex].top = y
      this.designImages[this.activeImageIndex].width = width
      this.designImages[this.activeImageIndex].height = height
    },
    onResizestop(e, index) {
      // 拖动、缩放时，鼠标可能移除盒子外，这时需要标记下不属于失去焦点
      this.isBeforeStop = true;
    },
    onDrag (x, y) {
      this.designImages[this.activeImageIndex].isCenter = false
      this.designImages[this.activeImageIndex].left = x
      this.designImages[this.activeImageIndex].top = y
    },
    onDragstop() {
      this.isBeforeStop = true;
    },
    handleDesignRemove() {
      this.designImages.splice(this.activeImageIndex, 1)
    },
    // 点击设计图外非编辑区域，则失去图片焦点
    onAnoDesignClick(e) {
      console.log(e, '--onAnoDesignClick----', this.activeMenuIndex)
      if (!e.target.className) {
        this.setActiveImageIndex(-1)
      }
      let isEdit = e.path.some(item => {    // 编辑区域、图像区域不失去编辑焦点
        if (item.className) {
          return item.className.indexOf('panel-content') > -1 || item.className.indexOf('design-itemBox') > -1
        }
        return false
      })
      // console.log(!isEdit, !this.isBeforeStop, '--onAnoDesignClick-', e)
      if (!isEdit && !this.isBeforeStop) {
        this.setActiveImageIndex(-1)
        if (!this.isActiveMenu) {
          this.setActiveDesignMenuIndex(-1);
          this.setActiveDesignComponent('')
        }
        this.isActiveMenu = false
      }
      this.isBeforeStop = false;
    }
  }
};
</script>
<style lang="less">
.ano-panel {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  position: relative;
  user-select: none;
  .ano-panel-bd {
    flex: 1;
    max-height: 560px;
    overflow-y: auto;
    padding-left: 15px;
    padding-right: 15px;
  }
  .section-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 0;
    .label {
      height: 40px;
      line-height: 40px;
    }
    .cnt {
      flex: 1;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: flex-end;
    }
    .handle-wrap {
      text-align: right;
    }
    .result {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      cursor: pointer;
    }
    .res-img {
      max-height: 100%;
      cursor: pointer;
    }
    .result-color {
      .res-colorName {
        display: inline-block;
      }
      .res-color {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 1px solid #eee;
        border-radius: 2px;
        margin-left: 10px;
      }
    }
    .el-icon-arrow-right {
      cursor: pointer;
    }
  }
  .el-input__inner {
    height: 40px;
    line-height: 40px;
    text-align: center;
    border-radius: @input-border-radius;
  }
  .panel-input-sort {
    width: 60px;
    margin-left: auto;
    margin-bottom: 0;
    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
  }
  // .el-button--mini, 
  // .el-button--small {
  //   border-radius: @input-border-radius;
  // }
}
.ano-panel-default {
  text-align: center;
  .hd {
    color: #333;
    font-size: 18px;
    padding-top: 30px;
  }
  .menu-list {
    max-width: 360px;
    display: flex;
    flex-wrap: wrap;
    margin: 25px auto 0;
    .item {
      width: 50%;
      margin-bottom: 20px;
      cursor: pointer;
      user-select: none;
      .pic {
        width: 104px;
        height: 72px;
        margin: 0 auto;
      }
    }
    .item:nth-child(1) .pic {
      background: url(../../assets/imgs/def-menu-1.svg) no-repeat center;
      background-size: 100% auto;
    }
    .item:nth-child(2) .pic {
      background: url(../../assets/imgs/def-menu-2.svg) no-repeat center;
      background-size: 100% auto;
    }
    .item:nth-child(3) .pic {
      background: url(../../assets/imgs/def-menu-3.svg) no-repeat center;
      background-size: 100% auto;
    }
    .item:nth-child(4) .pic {
      background: url(../../assets/imgs/def-menu-4.svg) no-repeat center;
      background-size: 100% auto;
    }
  }
  .fd {
    .stg {
      color: #1f51cf;
    }
  }
}
.design-itemBox {
  position: absolute;
  left: 0;
  top: 0;
  border: 0;
  &:hover {
    outline: #999 dashed 1px;
  }
  &.active {
    .design-close,
    .design-zoom {
      display: block;
    }
  }
  .design-box-wrap,
  .design-box-img {
    position: relative;
    width: 100%;
    height: 100%;
    max-width: 100%;
    max-height: 100%;
    overflow: hidden;
    &.ano-rotateY180 {
      transform: rotateY(180deg);
    }
    &.ano-rotateX180 {
      transform: rotateX(180deg);
    }
  }
  .design-box-lay {
    position: absolute;
    z-index: -99;
    opacity: 0;
  }
  .design-close,
  .design-zoom {
    display: none;
    position: absolute;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 1px solid #999;
    user-select: none;
  }
  .design-close {
    left: -28px;
    top: -28px;
    background: url(../../assets/imgs/icon-close.png) no-repeat center;
    background-size: 75% auto;
    cursor: pointer;
  }
  .design-zoom {
    bottom: -28px;
    right: -28px;
    background: url(../../assets/imgs/icon-zoom.png) no-repeat center;
    background-size: 75% auto;
    cursor: nw-resize;
  }
}
</style>

<style lang="less" scoped>
.ano-design {
  // background-color: #ddd;
}
.ano-design-container {
  display: flex;
  justify-content: space-between;
  background-color: #ddd;
}
.design-panel {
  position: relative;
  height: 600px;
  display: flex;
  z-index: 1;
  background-color: #fff;
  margin-left: 20px;
  margin-top: 20px;
  .panel-menus {
    width: 80px;
    font-size: 14px;
    text-align: center;
    background-color: #b3aee640;
    .item {
      margin-bottom: 12px;
      padding-bottom: 8px;
      cursor: pointer;
      &.active {
        background-color: #fff;
      }
    }
    .icon {
      width: 40px;
      height: 40px;
      margin: 0 auto;
      background-repeat: no-repeat;
      background-position: center;
      background-size: 80% auto;
    }
    .icon-text {
      background-image: url(../../assets/imgs/icon-text.png);
    }
    .icon-image {
      background-image: url(../../assets/imgs/icon-image.png);
    }
    .icon-upload {
      background-image: url(../../assets/imgs/icon-upload.png);
    }
    .icon-color {
      background-image: url(../../assets/imgs/icon-color.png);
    }
    .icon-note {
      background-image: url(../../assets/imgs/icon-note.png);
    }
  }
  .panel-content {
    width: 400px;
  }
}
.design-canvas {
  flex: 1;
  position: relative;
}
.canvas-sample {
  width: 720px;
  height: 800px;
  margin-left: auto;
  overflow: hidden;
  .pic {
    max-width: 100%;
  }
}
.canvas-main {
  position: absolute;
  right: 190px;
  top: 110px;
  width: 340px;
  height: 450px;
  border: 1px solid transparent;
  &.selected {
    border: 1px solid #000;
  }
}
</style>
